package dk.itu.samd.group2.tagapastry.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class TitleGenerator {

	private HashAlgorithm algorithm = HashAlgorithm.SHA_1;
	private boolean addSep;
	private MessageDigest md;
	
	public TitleGenerator() {
		this(HashAlgorithm.SHA_1,false);
	}
	
	/*
	 * By default don't use dashes
	 */
	public TitleGenerator(HashAlgorithm alg) {
		this(alg,false);
	}
	
	public TitleGenerator(HashAlgorithm alg, boolean addSep) {
		if(algorithm != alg)
			algorithm = alg;
		
		try {
			switch(algorithm) {
				case SHA_1: md = MessageDigest.getInstance("SHA-1");
				break;
				case MDA5: md = MessageDigest.getInstance("MDA5");
				break;
				default: md = null;
				break;
			}
			
			this.addSep = addSep;
			
		}catch (NoSuchAlgorithmException e) {
			return;
		}
	}
	
	public String generateTitle(String s) {
		
		//try {
			//MessageDigest md = MessageDigest.getInstance(algorithm.toString());
			md.update(s.getBytes());
			byte[] digest = md.digest();

			StringBuffer sb = new StringBuffer();
			int dash = 0;
			int tmp = 0;
			for(int i = 0; i < digest.length; i++) {
				sb.append(String.format("%02X", digest[i] & 0xff ));
				
				if(addSep) {
					dash = sb.length() - tmp;
					if(dash % 4 == 0 && i != digest.length-1) {
						sb.append("-");
						tmp++;
					}
				}
			}
			
			return sb.toString();
			
//		} catch (NoSuchAlgorithmException e) {
//			return null;
//		}
		
	}
	
}
